import _ from "lodash";
import fs from "fs-extra";
import path from "path";
import { BaseTask, TaskResult } from "./BastTask.js";
import { toolchain } from "../../toolchain.js";

export class CompileCSharpTask extends BaseTask {
    async run(): Promise<TaskResult<void>> {
        // C#脚本需要在一开始就编译，否则会报错
        const params = ['-batchmode', '-projectPath', toolchain.params.workSpacePath];
        // 调用设置platform，否则webgl首次打包的AB包platform不正确
        const csRoot = path.join(toolchain.params.workSpacePath, 'Assets/Editor/Builder/BuildCommand.cs');
        const content = await fs.readFile(csRoot, 'utf-8');
        if (content.includes('SetBuildPlatform')) {
            // 兼容某些旧项目没有SetBuildPlatform
            params.push('-executeMethod', 'BuildCommand.SetBuildPlatform');
        }
        params.push('-platform', this.cmdOption.platform, '-quit');
        await toolchain.unity.runUnityCommand(this.cmdOption, params, 'C#', true);
        return { success: true, errorCode: 0 };
    }
}
